<?php

namespace PhpSeverless;

class Manager
{
    public static $pool;

    public static $namespace = '\\PhpSeverless\\Adapter\\';

    public static $proxy;

    public static $phpCgi;

    public static function startPhpCGI($options = [])
    {
        if (self::$phpCgi) {
            return self::$phpCgi;
        }

        self::$phpCgi = new PhpCGI($options);

        return self::$phpCgi;
    }

    public static function getCgiClient($options = []): FastCGIClient
    {
        return new FastCGIClient($options);
    }

    public static function getAdapter($name)
    {
        if (!empty(self::$pool[$name])) {
            return self::$pool[$name];
        }

        $adapter = self::$namespace . ucfirst($name);
        self::$pool[$name] = new $adapter;

        return self::$pool[$name];
    }

    public static function __callStatic($name, $params)
    {
        $cgi = self::startPhpCGI();

        $adapter = self::getAdapter($name);
        $request = $adapter->handleRequest($params[1]);

        $client = self::getCgiClient($params[0]);

        try {
            $response = $client->request($request);
        } catch (\Exception $e) {
            $cgi->start();
            $response = $client->request($request);
        }

        return $adapter->handleResponse($response);
    }
}
